package com.example.ramcache.orm.impl;

import org.hibernate.StatelessSession;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.StatelessSessionImpl;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;

class HibernateHelper {
    @Resource
    private EntityManagerFactory entityManagerFactory;
    private SessionFactoryImplementor sessionFactory;

    public void init() {
        this.sessionFactory = entityManagerFactory.unwrap(SessionFactoryImplementor.class);
    }

    public SessionFactoryImplementor getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactoryImplementor sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public <T> T execute(Callback<T> action) {
        try (StatelessSession session = sessionFactory.openStatelessSession()) {
            T result = action.call((StatelessSessionImpl)session);
            return result;
        }
    }
}
